from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship, backref
import pymysql
import hashlib
from mydb import *
pymysql.install_as_MySQLdb()


app = Flask(__name__)

class Config(object):
    """配置参数"""
    # 设置连接数据库的URL
    user = 'root'
    password = 'Rootroot123'
    database = 'zwx_test'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://%s:%s@120.24.51.141:3306/%s' % (user,password,database)

    # 设置sqlalchemy自动更跟踪数据库
    SQLALCHEMY_TRACK_MODIFICATIONS = True

    # 查询时会显示原始SQL语句
    app.config['SQLALCHEMY_ECHO'] = True

    # 禁止自动提交数据处理
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = False

# 读取配置
app.config.from_object(Config)

# 创建数据库sqlalchemy工具对象
db = SQLAlchemy(app)


# rel: https://www.cnblogs.com/wanggungun/p/14933850.html
class Owner(db.Model):
    __tablename__ = 'owner'
    oid = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(255))
    password = db.Column(db.String(255))
    api_token = db.Column(db.String(255))

    def __repr__(self):  # 自定义 交互模式 & print() 的对象打印
        return "(%s, %s, %s, %s)" % (self.oid, self.username, self.password, self.api_token)

class Guest(db.Model):
    __tablename__ = 'guest'
    gid = db.Column(db.Integer, primary_key=True, autoincrement=True)
    gname = db.Column(db.String(255))
    facetoken = db.Column(db.String(255))
    oid = db.Column(db.Integer, db.ForeignKey("Owner.oid"))
    # owner = relationship("owner", backref("guest"))

    def __repr__(self):  # 自定义 交互模式 & print() 的对象打印
        return "(%s, %s, %s, %s)" % (self.gid, self.gname, self.facetoken, self.oid)


@app.route('/hello')
def hello_world():  # put application's code here
    return 'Hello World!'


@app.route('/user/login', methods=['POST'])
def login():
    username = request.form.get("username")
    password = request.form.get("password")
    md5 = hashlib.md5()
    md5.update(password.encode('utf-8'))
    password = md5.hexdigest()
    owners = Owner.query.filter_by(username=username).all()
    if owners:
        if password == owners[0].password:
            return ResBean.success("登陆成功", owners[0])
        else:
            return ResBean.error("密码错误")
    else:
        return ResBean.error("用户不存在")

@app.route('/user/register', methods=['POST'])
def register():
    username = request.form.get("username")
    password = request.form.get("password")
    md5 = hashlib.md5()
    md5.update(password.encode('utf-8'))
    password =md5.hexdigest()
    api_token = request.form.get("api_token")
    owners = Owner.query.filter_by(username=username).all()
    if owners:
        return ResBean.error("该用户名已存在")
    else:
        owner = Owner(username=username, password=password, api_token=api_token)
        db.session.add(owner)
        db.session.commit()
        return ResBean.success("用户" + username + "注册成功")

@app.route('/user/getGuests', methods=['GET'])
def get_guests():
    oid = request.args.get("oid")
    guests = Guest.query.filter_by(oid=oid).all()
    return ResBean.success("查询成功", guests)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001, debug = True)
